package chances.wechat.utils.taglib;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import chances.epg.commons.utils.SpringWebUtils;
import chances.wechat.model.WechatToken;
import chances.wechat.service.GatewayService;

public class WechatConfigTag extends TagSupport {

	private static final long serialVersionUID = -1310702916786135428L;
	private boolean debug;
	private String apiString;
	private String url;
	private String var;

	@Override
	public int doStartTag() throws JspException {
		GatewayService gatewayService  = SpringWebUtils.findBean((HttpServletRequest)pageContext.getRequest(), 
				GatewayService.class);
		WechatToken token = gatewayService.getToken();
		String nonceStr = create_nonce_str();
		long timeStamp = System.currentTimeMillis() / 1000L;
		String signature = SignUtil.getJsSdkSign(nonceStr, token.getJsToken(), ""+timeStamp, this.url);
		Map<String,String> map = new HashMap<String,String>();
		map.put("timestamp", ""+timeStamp);
		map.put("noncestr", nonceStr);
		map.put("signature", signature.toLowerCase());
		map.put("token",token.getToken());
		map.put("appId", token.getAppId());
		pageContext.setAttribute(var, map);
		pageContext.setAttribute("appId", token.getAppId());		
		return super.doStartTag();
	}

	public void release() {
		debug = false;
		apiString = "";
		super.release();
	}

	public static String create_nonce_str() {
		return UUID.randomUUID().toString();
	}

	public boolean isDebug() {
		return debug;
	}

	public void setDebug(boolean debug) {
		this.debug = debug;
	}

	public String getApiString() {
		return apiString;
	}

	public void setApiString(String apiString) {
		this.apiString = apiString;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}

}
